import numpy as np
def fit(x,y,m,w):
    if len(x)<=m:
        return False
    xishu = np.polyfit(x,y,m,w=w)
    p = np.poly1d(xishu) # 构造多项式
    yfit = p(x) # 拟合的y值
    yresid = y - yfit # 残差
    SSresid = sum(pow(yresid, 2)) # 残差平方和
    SStotal = len(y) * np.var(y) # 总体平均方差
    if SStotal==0:#水平线
        r2=1
    else:
        r2 = 1 - SSresid/SStotal # 拟合优度    
    return (xishu,r2,yfit)
if __name__=="__main__":
    x = np.arange(0,5,0.1)
    z = [2+3*x+4*x**2 for x in x]
    y = np.array([np.random.normal(z,3) for z in z])
    weight=[1 for one in x]
    print(fit(x,y,2,weight))
